<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="600px"
    @close="close"
  >
    <el-card shadow="hover">
      <el-form ref="extraForm" :model="extraForm" label-width="100px">
        <!-- 添加户型 -->
        <el-button type="primary" @click="addHouse">新增户型</el-button>
        <el-form-item
          v-for="(house, index) in Houses"
          :key="house.key"
          label="户型名称"
          :prop="'house.' + index + '.value'"
        >
          <el-row :gutter="10">
            <el-col :span="18">
              <el-input v-model="house.value" disabled></el-input>
            </el-col>
            <el-col :span="4">
              <el-button @click.prevent="removeHouseType(house)">
                删除
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-card>
    <el-dialog
      append-to-body
      title="新增户型"
      :visible.sync="dialogHouseTypeVisible"
      width="700px"
      @close="closeHouseType"
    >
      <el-form
        ref="houseTypeForm"
        :model="houseTypeForm"
        :rules="houseRules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="户型名称" prop="houseTypeId">
              <el-select
                v-model="houseTypeForm.houseTypeId"
                collapse-tags
                placeholder="请选择"
                size="medium"
              >
                <el-option
                  v-for="item in houseTypeIds"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="建筑面积(平方米)" prop="constructionArea">
              <el-input-number
                v-model.trim="houseTypeForm.constructionArea"
                autocomplete="off"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标签" prop="estatesTags">
              <el-select
                v-model="houseTypeForm.estatesTags"
                multiple
                placeholder="请选择"
                size="medium"
              >
                <el-option
                  v-for="item in houseTags"
                  :key="item.constantId"
                  :label="item.constantValue"
                  :value="item.constantId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="每平米价格(万元)" prop="price">
              <el-input-number
                v-model.trim="houseTypeForm.price"
                autocomplete="off"
                :min="0"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="图片（一张）" prop="imgId">
          <el-upload
            ref="imageUrl"
            :file-list="imageUrlfileList"
            action="imageUrl"
            :before-upload="imageUrlBeforeUpload"
            name="file"
            :http-request="uploadImage"
            list-type="picture-card"
            limit="1"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeHouseType">取 消</el-button>
        <el-button type="primary" @click="addHousesType">添 加</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import { setExtraInfo } from '@/api/building'
  import { getByType, getHouseType } from '@/api/tag'
  import { addHouseType, getAllHouseType, deleteHouseType } from '@/api/house'
  import { upload } from '@/api/upload'
  import _ from 'lodash'
  export default {
    name: 'AddHouseType',
    data() {
      return {
        buildingTags: [],
        houseTags: [],
        houseTypeIds: [],
        buildingTagsValue: [],
        imageUrlfileList: [],
        extraForm: {
          estateId: '',
          imgs: [],
          priceMax: 0,
          priceMin: 0,
          tags: [],
        },
        buildingVo: [],
        Houses: [],
        houseRules: {
          estatesTags: [
            { required: true, trigger: 'blur', message: '请选择户型标签' },
          ],
          houseTypeId: [
            { required: true, trigger: 'blur', message: '请选择户型名称' },
          ],
          priceMax: [
            { required: true, trigger: 'blur', message: '请输入最高价格' },
          ],
          imgId: [
            { required: true, trigger: 'blur', message: '请上传户型图片' },
          ],
        },

        houseTypeForm: {
          businessRealEstateId: '',
          constructionArea: 0,
          estatesTags: '',
          houseTypeId: '',
          imgId: '',
          price: 0,
        },
        title: '',
        dialogFormVisible: false,
        dialogHouseTypeVisible: false,
        show: false,
      }
    },
    methods: {
      //添加户型
      addHousesType() {
        let item = _.cloneDeep(this.houseTypeForm)
        item.price = Number(this.houseTypeForm.price)
        item.constructionArea = Number(this.houseTypeForm.constructionArea)
        item.businessRealEstateId = this.buildingVo.floorId
        //处理estatesTags
        item.estatesTags = this.houseTypeForm.estatesTags.toString()
        if (item.constructionArea == 0) {
          this.$baseMessage('建筑面积不能为0', 'error')
          return
        } else if (item.price == 0) {
          this.$baseMessage('价格不能为0', 'error')
          return
        }
        this.$refs['houseTypeForm'].validate(async (valid) => {
          if (valid) {
            const { data } = await addHouseType(item)
            if (data.status == 0) {
              // this.Houses.push({
              //   value:
              //     this.houseTypeIds[this.houseTypeForm.houseTypeId].typeName,
              //   key: Date.now(),
              // })

              this.$baseMessage('新建成功！', 'success')
              this.getBindHouseType()
              this.dialogHouseTypeVisible = false

              // this.closeHouseType()
            } else {
              this.$message.error(data.message)
            }
          } else {
            return false
          }
        })
      },
      imageUrlBeforeUpload(file) {
        let isRightSize = file.size / 1024 / 1024 < 2
        if (!isRightSize) {
          this.$message.error('文件大小超过 2MB')
        }
        return isRightSize
      },
      async uploadImage(param) {
        const formData = new FormData()
        formData.append('fileType', 1)
        formData.append('file', param.file)
        console.log(formData)
        const { data } = await upload(formData)
        this.dialogHouseTypeVisible
          ? (this.houseTypeForm.imgId = data.body.fileId)
          : this.extraForm.imgs.push(data.body.fileId)
      },
      //获取绑定后过的户型
      async getBindHouseType() {
        const { data } = await getAllHouseType({
          businessEstateId: this.extraForm.estateId,
        })
        if (data.status === 0) {
          if (data.body.length != 0) {
            let _array = data.body
            this.Houses = []
            for (let index = 0; index < _array.length; index++) {
              let item = {}
              item.value = _array[index].houseTypeNme
              this.Houses.push(item)
            }
          }
        }
      },
      showEdit(row) {
        if (row) {
          this.title = '户型配置'
          this.show = true
          this.Houses = []
          this.buildingVo = Object.assign({}, row)
          this.extraForm.estateId = row.floorId
          this.fetchBuildingTagData()
          this.fetchHouseTagData()
          this.fetchHouseIdData()
          this.getBindHouseType()
        }
        this.dialogFormVisible = true
      },
      close() {
        console.log('准备关闭')
        // this.$refs['extraForm'].resetFields()
        this.dialogFormVisible = false
        this.extraForm = {
          estateId: '',
          imgs: [],
          priceMax: 0,
          priceMin: 0,
          tags: [],
        }
      },
      closeHouseType() {
        this.dialogHouseTypeVisible = false
        // this.$refs['houseTypeForm'].resetFields()
        this.houseTypeForm = {
          businessRealEstateId: '',
          constructionArea: 0,
          estatesTags: '',
          houseTypeId: '',
          imgId: '',
          price: 0,
        }
      },
      // 保存额外信息
      save() {
        if (this.extraForm.tags.length == 0) {
          this.$baseMessage('请上传样图', 'error')
          return 0
        } else if (this.extraForm.priceMax == 0) {
          this.$baseMessage('最高价不能为0', 'error')
        } else if (this.extraForm.priceMin == 0) {
          this.$baseMessage('最低价不能为0', 'error')
        }
        this.$refs['extraForm'].validate(async (valid) => {
          if (valid) {
            let item = _.cloneDeep(this.extraForm)
            item.tags = this.extraForm.tags.toString()
            item.imgs = this.extraForm.imgs.toString()
            item.priceMax = Number(item.priceMax)
            item.priceMin = Number(item.priceMin)
            const { data } = await setExtraInfo(item)
            this.$baseMessage(data.message, 'success')
            this.$emit('fetch-data')
            this.close()
          }
        })
      },
      async fetchBuildingTagData() {
        let pushData = {}
        pushData.type = 4
        const { data } = await getByType(pushData)
        this.buildingTags = data.body
        this.$baseNotify('地产标签获取完毕！', '成功', 'success', 'top-right')
      },
      async fetchHouseTagData() {
        let pushData = {}
        pushData.type = 2
        const { data } = await getByType(pushData)
        this.houseTags = data.body
        this.$baseNotify('房源标签获取完毕！', '成功', 'success', 'top-right')
      },
      async fetchHouseIdData() {
        const { data } = await getHouseType()
        this.houseTypeIds = data.body
        this.$baseNotify('房源ID获取完毕！', '成功', 'success', 'top-right')
      },
      async removeHouseType(item) {
        console.log(item)
        //todo;删除户型 deleteHouseType
        // const { data } = await deleteHouseType(item)
        if (data.status == 0) {
          // this.Houses.push({
          //   value:
          //     this.houseTypeIds[this.houseTypeForm.houseTypeId].typeName,
          //   key: Date.now(),
          // })

          this.$baseMessage('删除成功！', 'success')
          this.getBindHouseType()
          // this.dialogHouseTypeVisible = false
          // this.closeHouseType()
        } else {
          this.$message.error(data.message)
        }
        // let index = this.Houses.indexOf(item)
        // if (index !== -1) {
        //   this.Houses.splice(index, 1)
        // }
      },
      addHouse() {
        this.dialogHouseTypeVisible = true
      },
    },
  }
</script>
<style lang="scss" scoped>
  .vab-upload {
    z-index: 9999 !important;
  }
</style>
